//
//  AGNetRequestHistoryVC.swift
//  AG_Test
//
//  Created by AG on 2020/12/2.
//

import UIKit

class AGNetRequestHistoryVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    var dataArray = [Any]()
    private let urlStr = "https://api.github.com/"
    var tableView: UITableView!
    var index: NSInteger = 0
    var nowIndex: NSInteger = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        self.title = "历史记录"
        self.index = UserDefaults.standard.integer(forKey: "index")
        self.nowIndex = self.index
        self.createTableView()
        self.loadData()
    }
    
    func createTableView() {
        
        self.tableView = UITableView.init(frame: CGRect.zero, style: .plain)
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.register(AGNetRequestHistoryCell.self, forCellReuseIdentifier: NSStringFromClass(AGNetRequestHistoryCell.self))
        self.tableView.separatorStyle = .none
        self.view.addSubview(self.tableView)
        self.tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        self.initRefresh()
    }
    
    func initRefresh() {
        let mj_footer = MJRefreshAutoNormalFooter()
        
        mj_footer.setRefreshingTarget(self, refreshingAction: #selector(footerLoad))
        mj_footer.stateLabel.isHidden = true
        mj_footer.isAutomaticallyRefresh = false
        mj_footer.isAutomaticallyChangeAlpha = true
        self.tableView.mj_footer = mj_footer
    }
    
    func loadData() {
        if self.nowIndex == 0 {
            return
        } else {
            let archiveURL = self.localPath()
            self.handleWithPath(archiveURL)
        }
    }
    
    func localPath() -> URL {
        let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let archiveURL = documentDirectory.appendingPathComponent("hisdory_\(self.nowIndex).plist")
        return archiveURL
    }
    
    func handleWithPath(_ archiveURL: URL) {
        do {
            let data = try Data.init(contentsOf: archiveURL)
            let obj = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data)
            if let arr = obj as? [Any]  {
                // 刷新数据
                let array = arr.reversed()
                self.dataArray.append(contentsOf: array)
                self.tableView.reloadData()
            }
        } catch {
            print("获取data数据失败: \(error)")
        }
    }
    
    @objc func footerLoad() {
        if self.nowIndex >= 2 {
            self.nowIndex -= 1
            let archiveURL = self.localPath()
            self.handleWithPath(archiveURL)
        }
        self.tableView.mj_footer.endRefreshing()
        self.tableView.mj_footer.state = .noMoreData
        return
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 64;
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let dic = self.dataArray[indexPath.row] as! [String: Any]
        let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(AGNetRequestHistoryCell.self)) as! AGNetRequestHistoryCell
        let str = dic["date"] as! String
        cell.refresh(str)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let dic = self.dataArray[indexPath.row] as! [String: Any]
        let vc = AGNetRequestHistoryDetailVC.init()
        vc.dic = dic
        self.navigationController?.pushViewController(vc, animated: true)
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
